﻿using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

namespace AutoCADDotNetLibrary.Analyzers.Analyzers
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class IExtensionApplicationAnalyzer : DiagnosticAnalyzer
    {
        public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ACDiagnostic.Rule_AC0001);

        public override void Initialize(AnalysisContext context)
        {
            context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
            context.EnableConcurrentExecution();
            context.RegisterCompilationStartAction(compilationStartAnalysisContext =>
            {
                //得到IExtensionApplication类
                List<(string TypeName, Location Location)> typeList = new List<(string TypeName, Location Location)>();
                compilationStartAnalysisContext.RegisterSymbolAction(symbolAnalysisContext =>
                {
                    INamedTypeSymbol namedTypeSymbol = symbolAnalysisContext.Symbol as INamedTypeSymbol;
                    if (namedTypeSymbol == null)
                        return;

                    if (namedTypeSymbol.AllInterfaces.FirstOrDefault(x => x.ToDisplayString() == "Autodesk.AutoCAD.Runtime.IExtensionApplication") == null)
                        return;

                    typeList.Add((namedTypeSymbol.ToDisplayString(), namedTypeSymbol.Locations.FirstOrDefault()));
                }, SymbolKind.NamedType);

                //判断
                compilationStartAnalysisContext.RegisterCompilationEndAction(symbolAnalysisContext =>
                {
                    typeList.ForEach(x =>
                    {
                        symbolAnalysisContext.ReportDiagnostic(
                            Diagnostic.Create(ACDiagnostic.Rule_AC0001, x.Location, x.TypeName));
                    });
                });
            });
        }
    }
}
